﻿using EasyNetQ;
using EasyNetQ.Topology;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace litedbdemo
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //"fanoutec", "fanouteckequeue", "fanouteckey"
            Ec ec = new Ec()
            {
                EcKey = Guid.NewGuid().ToString(),
                Status = 1,
                ProtocolChannelState = "321"
            };
          richTextBox1.AppendText(JsonConvert.SerializeObject(ec));
            FanoutPush<Ec>(ec,"fanoutec", "fanouteckey");
        }
        private static IQueue CreateQueue(IAdvancedBus adbus, string queueName)
        {
            if (adbus == null) return null;
            if (string.IsNullOrEmpty(queueName)) return adbus.QueueDeclare();
            return adbus.QueueDeclare(queueName);
        }
        public static void FanoutConsume<T>(Action<T> handler, string exChangeName, string queueName, string routingKey) where T : class
        {
            var _connectionConfigName = "rabbitmq-default";
            var _connectionString = ConfigurationManager.AppSettings[_connectionConfigName] ?? "";
            using (var bus = RabbitHutch.CreateBus(_connectionString))
            {
                var adbus = bus.Advanced;
                var exchange = adbus.ExchangeDeclare(exChangeName, EasyNetQ.Topology.ExchangeType.Fanout);
                var queue = CreateQueue(adbus, queueName);
                adbus.Bind(exchange, queue, routingKey);
                adbus.Consume(queue, registration => {
                    registration.Add<T>((message, info) => {
                        handler(message.Body);
                    });
                });
            }
        }

        public bool FanoutPush<T>(T t, string exChangeName , string routingKey) where T : class
        {

            var _connectionConfigName = "rabbitmq-default";
            var _connectionString = ConfigurationManager.AppSettings[_connectionConfigName] ?? "";
            try
            {
                using (var bus = RabbitHutch.CreateBus(_connectionString))
                {
                    var exchange = bus.Advanced.ExchangeDeclare(exChangeName, ExchangeType.Fanout);
                    bus.Advanced.Publish(exchange, routingKey, false, new Message<T>(t));
                    return true;
                }
            }
            catch (Exception ex)
            {
                return false;
            }
        }
    }
}
